package edu.hunau.cxb19.oop.class26;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Arrays;

import org.junit.Test;

/**
 *
 * @author hb
 *
 *         2020-03-31 14:57:48
 */
public class ByteStreamTest {

	@Test
	public void readFileTest() {

		try (FileInputStream fis = new FileInputStream(".\\demo\\out01.txt");) {
			byte[] buff = new byte[0];
			int data = -1;
			while ((data = fis.read()) != -1) {
				buff = Arrays.copyOf(buff, buff.length + 1);
				buff[buff.length-1]=(byte)data;
			}
			//将byte数组中的数据转成字符
			String strs = new String(buff);
			System.out.println(strs);

		} catch (Exception e) {
			// 在控制台输出异常信息
			e.printStackTrace();
		}
	}
	
	@Test
	public void readFileTest2() {

		try (FileInputStream fis = new FileInputStream(".\\demo\\out01.txt");) {
			 File file=new File(".\\demo\\out01.txt");	
			byte[] buff = new byte[(int)file.length()];
			
			fis.read(buff);
			
			//将byte数组中的数据转成字符
			String strs = new String(buff);
			System.out.println(strs);

		} catch (Exception e) {
			// 在控制台输出异常信息
			e.printStackTrace();
		}
	}
	
	@Test
	public void copyFileTest01() {
		try (FileInputStream fis = new FileInputStream(".\\demo\\out01.txt");
			 FileOutputStream fos=new FileOutputStream(".\\demo\\copy01.txt");) {
			int datas=-1;
			while((datas=fis.read())!=-1){
			 	fos.write(datas);
			}
		    //调用刷新确保输入全部写入到文件中
			fos.flush();
		} catch (Exception e) {
			// 在控制台输出异常信息
			e.printStackTrace();
		}
	}
	
	@Test
	public void copyFileTest02() {
		try (FileInputStream fis = new FileInputStream(".\\demo\\out01.txt");
			 FileOutputStream fos=new FileOutputStream(".\\demo\\copy02.txt");) {
			byte[] buff=new byte[1024];
			int len=-1;
			while((len=fis.read(buff))!=-1){
			 	fos.write(buff,0,len);
			}
		    //调用刷新确保输入全部写入到文件中
			fos.flush();
		} catch (Exception e) {
			// 在控制台输出异常信息
			e.printStackTrace();
		}
	 
	}
	
	@Test
	public void copyFileTest03() {
		try (FileInputStream fis = new FileInputStream(".\\demo\\out01.txt");
			 BufferedInputStream bis=new BufferedInputStream(fis);
			 FileOutputStream fos=new FileOutputStream(".\\demo\\copy02.txt");
			 BufferedOutputStream bos=new BufferedOutputStream(fos)) {
			byte[] buff=new byte[1024];
			int len=-1;
			while((len=bis.read(buff))!=-1){
			 	bos.write(buff,0,len);
			}
		    //调用刷新确保输入全部写入到文件中
			fos.flush();
		} catch (Exception e) {
			// 在控制台输出异常信息
			e.printStackTrace();
		}
	 
	}
}
